package com.company;

import java.io.Serializable;
import java.util.List;

/**
 * Created by v on 16-12-20.
 */
public class MyLinkList<E> implements Serializable{
    private Node<E> head;

    private int size;

    public MyLinkList(){

    }

    public void add(E e){
        if(head==null){
            head=new Node<E>(e);
            size++;
            return;
        }

        while (head.next!=null){
            head=head.next;
        }

        head.next=new Node<E>(e);
        size++;
    }

    public boolean remove(Object e) {
        if(head==null){
            return false;
        }

        if(head.equals(e)){
            head=head.next;
        }

        while (head.next!=null){
            if(head.next.element.equals(e)){
                head.next=head.next.next;
                return true;
            }
        }

        size--;
        return false;
    }

    public E get(int index){
        if(index>=size){
            throw new IndexOutOfBoundsException(""+index);
        }

        Node<E> current=head;

        for(int i=0;i<index;i++){
            current=current.next;
        }

        return current.element;
    }

    public int size() {
        return size;
    }

    public boolean remove(int index){
        if(index>=size()){
            return false;
        }

        Node<E> current=head;

        if(index==0){
            head=head.next;
            size--;
            return true;
        }

        for(int i=1;i<index;i++){
            current=current.next;
        }

        current.next=current.next.next;
        size--;
        return true;
    }

    public Object[] toArray() {
        Object[] objects=new Object[size()];
        Node<E> current=head;

        for(int i=0;i<size();i++){
            objects[i]=current.element;
            current=current.next;
        }

        return objects;
    }

    public void set(E e,int index){
        Node<E> current=head;

        for(int i=0;i<index;i++){
            current=current.next;
        }

        current.element=e;
    }

    private static class Node<E> implements Serializable{
        E element;
        Node<E> next;

        public Node(E element){
            this.element=element;
        }
    }
}
